<template>
  <n-card :bordered="false" class="proCard">
    <BasicTable
      :columns="columns"
      :dataSource="tableDataSource"
      :row-key="(row) => row.id"
      ref="actionRef"
      :pagination="false"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="2300"
    >
      <template #tableTitle>
        <n-button type="primary" @click="handlerAddPackage">
          <template #icon>
            <n-icon>
              <PlusOutlined/>
            </n-icon>
          </template>
          添加壳包
        </n-button>
      </template>

      <template #toolbar>
        <n-space>
          <n-button type="error" @click="deletePackage">批量删除</n-button>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </n-space>
      </template>
    </BasicTable>
    <n-modal :mask-closable="false" style="width: 40%" v-model:show="showEditModal" :show-icon="false" preset="dialog"
             :title="editTitle">
      <AddSubPackage :defaultValue="updateUser" @submit="submitPackageInfo"></AddSubPackage>
    </n-modal>

    <n-modal :mask-closable="false" style="width: 40%" v-model:show="showDockParamsModal" :show-icon="false"
             preset="dialog"
             title="对接参数">
      <n-descriptions :column="1" label-placement="left" class="py-3" size='large'>
        <n-descriptions-item label="游戏名称">{{dockParamFormValue.gameName}}</n-descriptions-item>
        <n-descriptions-item label="游戏APPID">{{dockParamFormValue.appKey}}</n-descriptions-item>
        <n-descriptions-item label="游戏KEY">{{dockParamFormValue.gameKey}}</n-descriptions-item>
        <n-descriptions-item v-if="dockParamFormValue.downUrl" label="游戏访问地址">
          {{dockParamFormValue.downUrl}}
        </n-descriptions-item>
        <n-descriptions-item v-else label="游戏访问地址">暂无</n-descriptions-item>
      </n-descriptions>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="cancelDockSubmit">
            返回
          </n-button>
          <n-button type="primary" @click="copyDockBtn">复制</n-button>
        </n-space>
      </template>
    </n-modal>

  </n-card>
</template>

<script lang="ts" setup>
  import {computed, h, onMounted, reactive, ref, onActivated, unref} from 'vue';
  import {useDialog, useMessage} from 'naive-ui';
  import {BasicTable, TableAction} from '@/components/Table';
  import {BasicForm, FormSchema, useForm} from '@/components/Form/index';
  import {columns, registerHandler, TableItemAction} from './columns';
  import {PlusOutlined} from '@vicons/antd';
  import {useRouter} from 'vue-router';
  import {GameModel, getGameAll, registerGame, updateGame} from "@/api/game/game";
  import {
    deleteSubPackage,
    getAllPackage,
    getdockParm,
    registerPackage,
    Subpackage,
    updateSubPackage
  } from "@/api/game/subpackage";
  import AddSubPackage from "./addSubPackage.vue"
  import {copyToClipboard} from "@/utils/copyUtils";


  const router = useRouter();
  const dialog = useDialog();
  const formRef: any = ref(null);
  const checkRows = ref([]);
  const message = useMessage();
  const actionRef = ref();
  const tableDataSource = ref([]);
  const showEditModal = ref(false);
  const editTitle = ref("");
  const updateUser = ref({});
  const dockParamFormValue = ref({});
  const showDockParamsModal = ref(false);


  const formModel = {
    appDesc: "",
    appIcon: "",
    appKey: "",
    appName: "",
    appStatus: "",
    appType: "",
    chanId: "",
    chanName: "",
    createTime: "",
    downUrl: "",
    gameKey: "",
    gameName: "",
    id: 0,
    isPack: "",
    redStatus: "",
    updateTime: "",
  };


  const actionColumn = reactive({
    width: 260,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '对接参数',
            onClick: handleGameParam.bind(null, record),
            type: 'warning',
            ifShow: () => {
              return true;
            },
          },
          {
            label: '编辑',
            onClick: handleGameEdit.bind(null, record),
            type: 'info',
            ifShow: () => {
              return true;
            },
          },
          {
            label: '操作记录',
            type: 'error',
            onClick: handleGameRecord.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  function deletePackage() {
    let rows = unref(checkRows);
    if (rows && rows.length > 0) {
      dialog.warning({
        title: '提示',
        content: '您确定要删除渠壳包？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          let params = [];
          rows.forEach(key => {
            params.push(Object.assign({}, formModel, {id: key}));
          });
          await deleteSubPackage({arrs: params});
          message.success("删除成功");
          reloadTable()
        },
        onNegativeClick: () => {

        },
      })
    } else {
      message.error("必须选择一条数据");
    }
  }


  function handlerAddPackage() {
    editTitle.value = "添加游戏";
    updateUser.value = {
      redStatus: "able",
      isPack: "able",
      appStatus: "trial",
      appType: "andriod"
    };
    showEditModal.value = true
  }

  async function submitPackageInfo(gameMode: Subpackage) {
    if (gameMode.id) {
      await updateSubPackage(gameMode);
    } else {
      gameMode.id = 0;
      let obj = Object.assign({}, formModel, gameMode);
      await registerPackage(obj)
    }
    message.success("提交成功");
    showEditModal.value = false;
    reloadTable()
  }

  //处理对接参数
  async function handleGameParam(record: Recordable) {
    showDockParamsModal.value = true;
    let dockParam = await getdockParm(unref(record));
    let row: any = unref(dockParam);
    dockParamFormValue.value = Object.assign({}, {
      gameName: row.gameName,
      gameKey: row.gameKey,
      appKey: row.appKey,
      downUrl: row.downUrl
    })
  }

  function cancelDockSubmit() {
    showDockParamsModal.value = false;
  }

  async function copyDockBtn() {
    let copyText = `游戏名称:${dockParamFormValue.value.gameName}
游戏APPID:${dockParamFormValue.value.appKey}
游戏KEY:${dockParamFormValue.value.gameKey}
游戏访问地址:${dockParamFormValue.value.downUrl}`;
    await copyToClipboard(copyText);
    message.success("复制成功");
    cancelDockSubmit()

  }


  function handleGameEdit(record: Recordable) {
    editTitle.value = "编辑游戏";
    showEditModal.value = true;
    updateUser.value = Object.assign({}, record)
  }

  function handleGameRecord(record: Recordable) {

  }


  async function loadDataTable() {

    let data = await getAllPackage();
    tableDataSource.value = data ? data : []
  }

  function onCheckedRow(rowKeys) {
    checkRows.value = rowKeys;
  }

  function reloadTable() {
    loadDataTable();
    actionRef.value.reload();
  }


  onMounted(async () => {
    await loadDataTable()
  });

</script>

<style lang="less" scoped></style>
